#include "configmanager.h"

ConfigManager::ConfigManager(const QString &filePath)
    : filePath(filePath)
{
    loadConfig();
}

ConfigManager& ConfigManager::instance()
{
    static ConfigManager instance(":/resources/config.json");
    return instance;
}

bool ConfigManager::loadConfig()
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qWarning("Couldn't open config file.");
        return false;
    }

    QByteArray fileData = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(fileData, &parseError);

    if (parseError.error != QJsonParseError::NoError)
    {
        qWarning() << "JSON parse error:" << parseError.errorString();
        return false;
    }

    if (!jsonDoc.isObject())
    {
        qWarning("Invalid JSON format");
        return false;
    }

    config = jsonDoc.object();
    return true;
}

bool ConfigManager::saveConfig()
{
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qWarning("Couldn't open config file for writing.");
        return false;
    }

    QJsonDocument jsonDoc(config);
    file.write(jsonDoc.toJson());
    file.close();
    return true;
}

QJsonObject ConfigManager::getConfig() const
{
    return config;
}

void ConfigManager::setConfig(const QJsonObject &newConfig)
{
    config = newConfig;
}
